package util.bitmap;

import android.app.Application;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import java.io.File;
import java.text.DecimalFormat;

public class FileUtil
{
    private static Context context;

    public static void init(Application a)
    {
        context = a;
    }

    public static String getImgPath(String imageUrl)
    {
        return getFileDir().getPath() + "/" + imageUrl.hashCode() + ".jpg";
    }

    public static String getVoicePath(String voiceUrl)
    {
        return getFileDir().getPath() + "/" + voiceUrl.hashCode() + ".mp3";
    }

    public static String getGifPath(String imageUrl) {
        return getFileDir().getPath() + "/" + imageUrl.hashCode() + ".gif";
    }

    public static boolean exists(String imageUrl)
    {
        return new File(getImgPath(imageUrl)).exists();
    }

    public static boolean gifExists(String imageUrl) {
        return new File(getGifPath(imageUrl)).exists();
    }
    public static boolean voiceExists(String voiceUrl) {
        return new File(getVoicePath(voiceUrl)).exists();
    }
    public static File getCacheDir() {
        File f = null;
        f = context.getExternalCacheDir();
        if (f == null) {
            f = context.getCacheDir();
        }
        return f;
    }
    public static File getFileDir() {
        File f = null;
        f = context.getExternalFilesDir("");
        if (f == null) {
            f = context.getFilesDir();
        }
        return f;
    }

    public static String getPath(Context context, Uri uri)
    {
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = { "_data" };
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver().query(uri, projection, null, null, null);
                int index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    return cursor.getString(index);
                }
                cursor.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    public static String getFormatedFileSize(long fileSize)
    {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileSize < 1024L)
            fileSizeString = df.format(fileSize) + "B";
        else if (fileSize < 1048576L)
            fileSizeString = df.format(fileSize / 1024.0D) + "K";
        else if (fileSize < 1073741824L)
            fileSizeString = df.format(fileSize / 1048576.0D) + "M";
        else {
            fileSizeString = df.format(fileSize / 1073741824.0D) + "G";
        }
        return fileSizeString;
    }
}